package com.disdr.picture;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

public class 图片旋转 {
    JFrame jf = new JFrame();

    public static void main(String[] args) {
        new 图片旋转();
    }

    public 图片旋转() {
        inGui();
    }

    public void inGui() {
        TransJPanel canvas = new TransJPanel();
        jf.add(canvas);
        jf.setBounds(0, 0, 600, 680);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }

    //这是一个面板的类
    class TransJPanel extends JPanel {
        JButton jb = new JButton("旋转");
        BufferedImage img;
        BufferedImage img2;
        //旋转的角度。因为工程需要，代码中直接写成了90，可以根据具体需要动态修改，以符合实际情况
        int roteAngle = 0;

        public TransJPanel() {
            try {
                img = ImageIO.read(new File("E:\\output.png"));
                img2 = ImageIO.read(new File("E:\\output.png"));
            } catch (Exception e) {
                System.out.println("数据读入有错");
            }
            this.add(jb);
            jb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("待处理 旋转按钮");
                        setRotate();
                }
            });
        }
        public void paintComponent(Graphics g){
            super.paintComponent(g);// 第一个图显示在(0,0)的位置,
            g.drawImage(img, 0, 0, this);
            drawTransImage(g, 300, img.getHeight() + 20);
        }
        // 这是显示另外一个图片的方法
        public void drawTransImage (Graphics g,int drawx, int drawy){
            int w = img2.getWidth();
            int h = img2.getHeight();
            Graphics2D g2 = (Graphics2D) g;
            //设置一个新的原点
            g2.translate(drawx, drawy);
            //如果旋转的角度不为0一般点击按钮这个值都是在一直改变的
            if (roteAngle != 0) {
                // 旋转变换，[旋转弧度,x,y] (>〉右移一位，就是缩小两倍)旋转图像的原点确实就在 长和宽的一半处的,
                g2.rotate(Math.toRadians(roteAngle),w>>1,h >>1);
                //g2.drawImage(img2, 0, 0, w, h, 0, 0, w, h, null);
                g2.drawString("我是谁啊",300,50);
                g2.translate(-drawx, -drawy);//把坐标原点给变回去
            }
        }

        private void setRotate() {
            roteAngle += 45;
            roteAngle %= 360;
            repaint();
        }
    }

}